package cn.ekuma.epos.android.payment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.ekuma.epos.datalogic.I_DataLogicSales;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import cn.ekuma.epos.ui.android.R;

import com.openbravo.bean.Customer;
import com.openbravo.bean.PaymentInfo;
import com.openbravo.format.Formats;
import com.openbravo.pos.payment.PaymentInterface;
import com.openbravo.pos.payment.PaymentNotifier;
import com.openbravo.pos.payment.PaymentSelect;
import com.openbravo.pos.util.PaymentInfoList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;

public abstract class AbstractPDAPaymentSelect extends Activity implements PaymentNotifier,PaymentSelect, OnTabChangeListener, TabContentFactory {

    private PaymentInfoList m_aPaymentInfo;
    private boolean printselected;
    private boolean accepted;
    private double m_dTotal;
    private Customer customerext;
    private I_DataLogicSystem dlSystem;
    private I_DataLogicSales dlSales;
    
    private Map<String, PaymentInterface> payments = new HashMap<String, PaymentInterface>();
    private String m_sTransactionID;
    private TabHost tabHost;
    
    protected ImageButton btmAdd,btmSub,btmOk,btmCanncel;
    private TextView m_jRemaininglEuros,m_jTotalEuros;
    
    public static final String RETURN_PAYMENTINFO="ReturnPaymentInfo";
    
    public static final String IN_TOTALS="total";
    public static final String IN_CUSTOMER="customer";
    
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle mBundle=getIntent().getExtras();
		if(mBundle!=null){
			m_dTotal=mBundle.getDouble(IN_TOTALS);
			customerext=(Customer) mBundle.getSerializable(IN_CUSTOMER);
		}
		
		m_aPaymentInfo=new PaymentInfoList();
		this.setContentView(R.layout.payment_selecter);
		btmAdd=(ImageButton) this.findViewById(R.id.payment_selecter_add);
		btmAdd.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				 PaymentInfo returnPayment =payments.get(tabHost.getCurrentTabTag()).executePayment();
			        if (returnPayment != null) {
			        	if(returnPayment.getName().equalsIgnoreCase("voucher"))
			        		for(PaymentInfo p:m_aPaymentInfo.getPayments())
			        			if(p.getName().equalsIgnoreCase("voucher")&&p.getTransactionID().equalsIgnoreCase(returnPayment.getTransactionID())){
			        				//new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.voucherInPayment")).show(this);
			        				return;
			        			}
			            m_aPaymentInfo.add(returnPayment);
			            printState();
			        }
			}
			
		});
		
		btmSub=(ImageButton) this.findViewById(R.id.payment_selecter_sub);
		btmSub.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				 m_aPaymentInfo.removeLast();
			     printState();
			}
			
		});
		btmOk=(ImageButton) this.findViewById(R.id.payment_selecter_ok);
		btmOk.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				PaymentInfo returnPayment =payments.get(tabHost.getCurrentTabTag()).executePayment();
				if (returnPayment != null) {
					if (returnPayment.getName().equalsIgnoreCase("voucher"))
						for (PaymentInfo p : m_aPaymentInfo.getPayments())
							if (p.getName().equalsIgnoreCase("voucher")
									&& p.getTransactionID().equalsIgnoreCase(
											returnPayment.getTransactionID())) {
								// new MessageInf(MessageInf.SGN_WARNING,
								// AppLocal.getIntString("message.voucherInPayment")).show(this);
								return;
							}
					m_aPaymentInfo.add(returnPayment);
					accepted = true;
					// dispose();
					Intent data = new Intent();
					data.putExtra(RETURN_PAYMENTINFO, m_aPaymentInfo);
					setResult(1, data);
					finish();
		        }
				
			}
			
		});
		btmCanncel=(ImageButton) this.findViewById(R.id.payment_selecter_cancel);
		btmCanncel.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				// dispose();
				finish();
			}
			
		});
		
		m_jTotalEuros=(TextView) this.findViewById(R.id.payment_selector_totaleuros);
		m_jRemaininglEuros=(TextView) this.findViewById(R.id.payment_selector_remainingleuros);
		tabHost=(TabHost)findViewById(android.R.id.tabhost);
		tabHost.setup();
		
		addTabs();
		
		m_jTotalEuros.setText(Formats.CURRENCY.formatValue(new Double(m_dTotal)));
		printState();
		tabHost.setOnTabChangedListener(this);
	}

	public void setPrintSelected(boolean value) {
        printselected = value;
    }

    public boolean isPrintSelected() {
        return printselected;
    }

    public List<PaymentInfo> getSelectedPayments() {
        return m_aPaymentInfo.getPayments();
    }
    
    abstract void addTabs();
    
    protected void printState(){
    	m_jRemaininglEuros.setText(Formats.CURRENCY.formatValue(new Double(m_dTotal - m_aPaymentInfo.getTotal())));
    	btmSub.setEnabled(!m_aPaymentInfo.isEmpty());
    	
    	tabHost.setCurrentTab(0); // selecciono el primero
    	onTabChanged(tabHost.getCurrentTabTag());

    }

	public void onTabChanged(String tabId) {
		PaymentInterface currentPaymentInterface=payments.get(tabId);
		if(currentPaymentInterface!=null)
			currentPaymentInterface.activate(customerext, m_dTotal - m_aPaymentInfo.getTotal(), m_sTransactionID);
		
	}

	public void setStatus(boolean isPositive, boolean isComplete) {
		 setAddEnabled(isPositive && !isComplete);
	     setOKEnabled(isComplete);
	}

	private void setOKEnabled(boolean isComplete) {
		btmOk.setEnabled(isComplete);
		
	}

	private void setAddEnabled(boolean b) {
		btmAdd.setEnabled(b);
	}
	
	
	 protected void addTabPayment(PaymentCreator jpay) {
	        //if (RoleUtil.hasPermission(app.getAppUserView().getUser(),jpay.getKey())) {

	           // PaymentInterface jpayinterface = payments.get(jpay.getKey());
	           // if (jpayinterface == null) {
	           //     jpayinterface = (PaymentInterface) jpay.createTabContent(jpay.getKey());
	           //     payments.put(jpay.getKey(), jpayinterface);
	           // }

	            TabSpec tabSpec = (TabSpec)tabHost.newTabSpec(jpay.getKey()).setIndicator(jpay.getLabelKey()).setContent(this);
	            tabHost.addTab(tabSpec);
	           
	        //}
	  }

		public View createTabContent(String tag) {
		   if("payment.cash".equalsIgnoreCase(tag)){
			   PaymentCashPos p=new PaymentCashPos(this,this);
			   payments.put(tag, p);
			   return p;
		   }
			return null;
		}
	 
	public interface PaymentCreator {

		public String getKey();

		public String getLabelKey();

	    public int getIconKey();
	}
		
	 public class PaymentCashCreator implements PaymentCreator {

	        public PaymentCashCreator() {
			super();
		    }

			public String getKey() {
	            return "payment.cash";
	        }

	        public String getLabelKey() {
	            return "tab.cash";
	        }

	        public int getIconKey() {
	            return R.drawable.advanced;
	        }
	    }

	public void onEQUCommand() {
		if(btmAdd.isEnabled())
			btmAdd.performClick();
		else if(btmOk.isEnabled())
			btmOk.performClick();
	} 
}
